﻿



import Request from '../../base/request.js?t=202511041006'
import Storage from '../../base/storage.js?t=202511041006'
import { dealTime, queryURLParams, getRecentYears, getMonthList, getBrowserInfo, previewCom } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {

    const data = reactive({
        messageTest: "",
        proxy: "",
        popTitle: "",
        cIndex: 2,
  
        previewInfo: {
            pdfurl: "",
            pdfOpen: false,
            previewShow: false,
            imgUrl:""
        },
        uinfo: {

        },
        tabList: [
            {
                label:'公司级',value:1
            },{
                label:'部门级', value: 2
            }],
        statusList: [
            {
                label: '保存', value: 0
            }, {
                label: '发布', value: 1
            }],
        queryParams: {
            SupplyName: null,
            Time: null,
            Status:null
        },
        checkQueryParams: {
            Period: null,
        },
        urlinfo: {},
        uploadLock:false,
        opType: true,
        popShow: false,
        pagination: {
            total: 0,
            current: 1,
            pageSize: 10,
            loading: true,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 10,
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗
        },

        yearList: [

        ],
        monthList: [
        ],
        citem: {},
        columns: [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                align: 'center',
                width: 80,
                customRender: ({ index }) => {
                    return (params.pagination.value.current - 1) * params.pagination.value.pageSize + index + 1
                },
            },
            //{
            //    title: '物资内容',
            //    dataIndex: 'SupplyName',
            //    key: 'SupplyName',
            //    align: 'center'

            //},
            {
                title: '提交部门',
                dataIndex: 'DepartmentName',
                key: 'DepartmentName',
                align: 'center'
            },
            {
                title: '更新日期',
                dataIndex: 'UpdateTime',
                key: 'UpdateTime',
                align: 'center',
                customRender: function ({ text }) {
                    return dealTime(text, 'YYYY-MM-DD HH:mm')
                }
            },
            {
                title: '检查日期',
                dataIndex: 'LastCheckTime',
                key: 'LastCheckTime',
                align: 'center',
                customRender: function ({ text }) {
                    return text? dealTime(text, 'YYYY-MM-DD HH:mm'):"-"
                }

            },
            {
                title: '检查附件',
                dataIndex: 'LastFileList',
                key: 'LastFileList',
                align: 'center',
                customRender: function ({ text }) {
                    const getFileTypeByExtension=(fileName)=> {
                        const ext = fileName.split('.').pop().toLowerCase(); // 获取文件扩展名并转换为小写
                        if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'svg'].includes(ext)) {
                            return 'image';
                        } else if (ext === 'pdf') {
                            return 'pdf';
                        } else {
                            return false; // 或者其他逻辑
                        }
                    }
                    const downloadFile = (file) => {
                        // 创建隐藏的<a>元素
                        const a = document.createElement('a');
                        a.href = file.FilePath;
                        a.download = file.FileName; // 设置下载的文件名
                        document.body.appendChild(a);
                        a.click(); // 触发下载
                        document.body.removeChild(a); // 下载后移除元素
                    };
                    let content = text
                        ? text.map(file => {
                      
                            let btns = h('div', {}, [
                                getFileTypeByExtension(file.FileName) ? h('button', { onclick:()=> methods.handlePreview(file), style: 'margin-left:10px;color:#108ee9' }, '预览') : null,
                                h('button', { onclick:()=> downloadFile(file), style: 'margin-left:10px;color:#108ee9' }, '下载')
                            ])
                            return h('div', { style: 'margin:5px 0;width:100%;display:flex;justify-content:space-between' }, [
                                h('span', {}, file.FileName),
                                btns
                            ]);
                        })
                        : '-';

 
                    const tag = () => h(antd.Tag, {
                        color: "#108ee9",
                        style:"cursor:pointer"
                    }, { default: () => text?.length||0 })

                    let hdiv = () => h('div', {
                        style: `max-width: 600px;`
                    }, {
                        default: () => content
                    });
                    const pop = () => h(antd.Popover, {
                        title: '附件详情',
                        content: hdiv(),
                    }, () => [tag()]);

                    return  h('div', {
                    }, { default: () => [pop()] })

                },
            },
            {
                title: '状态',
                dataIndex: 'StatusName',
                key: 'StatusName',
                align: 'center',
                customRender: function ({ text }) {
                    return h(antd.Tag, {
                       
                    }, () => [text])
                }
            },
            {
                title: '操作',
                key: 'action',
                align: 'center',
                customRender: function ({ record }) {

                    const FDBtn = h(antd.Popconfirm, {
                        title: `提示：应急物资提交部门【${record.DepartmentName}】，删除后将无法恢复，请您确认。`,
                        onConfirm: () => methods.handleDelete(record)

                    }, { default: () => [delBtn] })

                    let detailBtn = h(antd.Button, {
                        type: "link",
                        onClick: () => {
                            methods.handleDetail(record)
                        }
                    }, { default: () => '详情' })

                    let editBtn = h(antd.Button, {
                        type: "link",
                        onClick: () => {
                            methods.handleEdit(record)
                        }
                    }, { default: () => '编辑' })

                    let reviewBtn = h(antd.Button, {
                        type: "link",
                        onClick: () => {
                            methods.handleReview(record)
                        }
                    }, { default: () => '检查' })

                    let reviewTableBtn = h(antd.Button, {
                        type: "link",
                        onClick: () => {
                            methods.handlereviewTable(record)
                        }
                    }, { default: () => '检查台账' })

                    let delBtn = h(antd.Button, {
                        type: "link",
                         danger:true
                    }, { default: () => '删除' })
                    return h('div', {
                    },
                        { default: () => [record.IsShowCheck ? reviewBtn : null, record.IsShowCheckRecord ? reviewTableBtn : null, record.IsEdit ? editBtn:null, record.IsDelete? FDBtn:null, detailBtn] }
                    );

                }
            },
        ],


        dataSource: [],

        PeriodList: [
            { label: '第一季度', value: 1 },
            { label: '第二季度', value: 2 },
            { label: '第三季度', value: 3 },
            { label: '第四季度', value: 4 },
        ],

        checkColumns: [
                {
                    title: '序号',
                    dataIndex: 'index',
                    key: 'index',
                    align: 'center',
                    width: 80,
                customRender: ({ index }) => {
                    return (params.checkPagination.value.current - 1) * params.checkPagination.value.pageSize + index + 1
                },
            },
            {
                title: '年度',
                dataIndex: 'Years',
                key: 'Years',
                align: 'center'
            },
                //{
                //    title: '物资内容',
                //    dataIndex: 'SupplyName',
                //    key: 'SupplyName',
                //    align: 'center'
                //},
                {
                    title: '检查部门',
                    dataIndex: 'DepartmentName',
                    key: 'DepartmentName',
                    align: 'center'
                },
                {
                    title: '检查日期',
                    dataIndex: 'UpdateTime',
                    key: 'UpdateTime',
                    align: 'center'
                },
                {
                    title: '检查季度',
                    dataIndex: 'Period',
                    key: 'Period',
                    align: 'center',
                    customRender: function ({ text }) {
                        return h(antd.Tag, {
                            color: '#0070d9'
                        }, () => text)
                    }
                },
                {
                    title: '物资状态',
                    dataIndex: 'IsNormal',
                    key: 'IsNormal',
                    align: 'center',
                    customRender: function ({ text }) {
                        return h(antd.Tag, {
                            color: text == true ? '#27d870' : '#e4454b'
                        }, () => text == true?'正常':'有异常')
                    }
                },
                {
                    title: '备注',
                    dataIndex: 'Remark',
                    key: 'Remark',
                    align: 'center'
            }, {
                title: '操作',
                key: 'action',
                align: 'center',
                customRender: function ({  record }) {


                   
                    let detailBtn = h(antd.Button, {
                        type: "link",
                        onClick: () => {
                            methods.handleCheckDetail(record)
                        }
                    }, { default: () => '详情' })

                
                    return h(antd.Space, {
                    },
                        { default: () => [detailBtn] }
                    );

                }
            },
            
        ],
        checkDataSource: [],
        checkPagination: {
            total: 0,
            current: 1,
            pageSize: 10,
            loading: true,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 10,
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗
        },
    })
    let params = toRefs(data)
    const methods = {
        tchange: () => {
            Storage.set(`${window.location.pathname}Index`, params.cIndex.value, true)
            params.queryParams.value = {
            }
            params.queryParams.value.LevelId = params.cIndex.value
            methods.getTableList(true)
        },
        toAdd: () => {
            window.location.href = `/EmergencyManagement/EMADD?l=${params.cIndex.value}`
        },
        handleOk: () => {
            params.popShow.value = false

        },
        handleDetail: (item) => {
            window.location.href = `/EmergencyManagement/EMADD?l=${params.cIndex.value}&id=${item.Id}&type=9`

        },
        handlePreview: (item) => {
            if (item.FileName.indexOf('.pdf') != -1) {
                params.previewInfo.value.pdfUrl = item.FilePath
                params.previewInfo.value.pdfOpen = true
            } else {
                params.previewInfo.value.imgUrl = item.FilePath
                params.previewInfo.value.previewShow=true
            }
        },
        handleCheckDetail: (item) => {
            window.open(`/EmergencyManagement/EMCHECK?l=${params.cIndex.value}&id=${item.FormId}&fid=${item.Id}&type=9`, "_self")
        },
        handleReview: (item) => {
            window.open(`/EmergencyManagement/EMCHECK?l=${params.cIndex.value}&id=${item.Id}`, "_self")
        },
        handleEdit: (item) => {
            window.location.href = `/EmergencyManagement/EMADD?l=${params.cIndex.value}&id=${item.Id}&type=1`
        },
        handlereviewTable: (item) => {
            params.citem.value = item
            params.checkQueryParams.value = {}
            methods.checkGetTableList(true)
            params.popShow.value=true
        },
        handleDelete: (item) => {
            Request({
                url: "/EmergencyPlan/DeleteEmergencySupplies",
                method: 'post',
                data: {
                    Id: item.Id
                }
            }).then(res => {
                params.messageTest.value.success(res.Msg);
                methods.getTableList(true)
            })

        },


        ITeamType: () => {
            return new Promise((resolve, rej) => {
                params.pagination.value.loading = true
                Request({
                    url: "/EmergencyPlan/GetEmergencyTeamType",
                    method: 'post',
                    data: {
                        type:"view"
                    }
                }).then(res => {
                    params.tabList.value = res.Data.map(e => ({
                        label: e.ConfigValue,
                        value: e.Id
                    }))
                    resolve()
                })
            })
        },
        filterOption: (val, type) => {
            return `${type.label}`.includes(`${val || ''}`)
        },

        checkHandleTableChange: (page) => {
            const { current, pageSize } = page
            params.checkPagination.value.current = current;
            params.checkPagination.value.pageSize = pageSize;
            methods.checkGetTableList()
        },
        handleTableChange: (page) => {
            const { current, pageSize } = page
            params.pagination.value.current = current;
            params.pagination.value.pageSize = pageSize;
            methods.getTableList()
        },
        checkGetTableList: async (isRresh) => {
            if (isRresh) {
                params.checkPagination.value.current = 1
                //params.queryParams.value = {}
            }
            params.checkPagination.value.loading = true

                Request({
                    url: "/EmergencyPlan/GetEmergencySuppliesCheckPageList",
                    method: 'post',
                    params: {
                        page: params.checkPagination.value.current,
                        pageSize: params.checkPagination.value.pageSize
                    },
                    data: {
                        Period: params.checkQueryParams.value.Period,
                        Years: params.checkQueryParams.value.Years,
                        FormId: params.citem.value.Id
                    }
                }).then(res => {
                    params.checkDataSource.value = res.Data.Data.map(e => {
                        return {
                            SupplyName: params.citem.value.SupplyName,
                            DepartmentName: params.citem.value.DepartmentName,
                            UpdateTime: dealTime(e.UpdateTime, 'YYYY-MM-DD HH:mm'),
                            Period: { 1: '第一季度', 2: '第二季度', 3: '第三季度', 4: '第四季度' }[e.Period],
                            IsNormal: e.IsNormal,
                            Remark: e.Remark,
                            Id: e.Id,
                            Years: e.Years,
                            FormId: e.FormId
                        }
                    })
                    params.checkPagination.value.total = res.Data?.TotalItemCount
                    params.checkPagination.value.loading = false

                })
      


        },

        getTableList: async (isRresh) => {
            if (isRresh) {
                params.pagination.value.current = 1
                //params.queryParams.value = {}
            }
            params.pagination.value.loading = true
            if (params.cIndex.value == 1) {
                Request({
                    url: "/EmergencyPlan/GetEmergencySuppliesList",
                    method: 'post',
                    params: {
                        page: params.pagination.value.current,
                        pageSize: params.pagination.value.pageSize
                    },
                    data: {
                        model: {
                            SupplyName: params.queryParams.value.SupplyName,
                            "StartTime": params.queryParams.value.Time&& dayjs(params.queryParams.value.Time[0]).format('YYYY-MM-DD'),
                            "EndTime": params.queryParams.value.Time&&dayjs(params.queryParams.value.Time[1]).format('YYYY-MM-DD'),
                             Status: params.queryParams.value.Status,
                            LevelId: params.cIndex.value,
              
                        }

                    }
                }).then(res => {
                    params.dataSource.value = res.Data.Data
                    params.pagination.value.total = res.Data?.TotalItemCount
                    params.pagination.value.loading = false
                })
            } else {
                Request({
                    url: "/EmergencyPlan/GetEmergencySuppliesList",
                    method: 'post',
                    params: {
                        page: params.pagination.value.current,
                        pageSize: params.pagination.value.pageSize
                    },
                    data: {
                        model: {
                            SupplyName: params.queryParams.value.SupplyName,
                            "StartTime": params.queryParams.value.Time && dayjs(params.queryParams.value.Time[0]).format('YYYY-MM-DD'),
                            "EndTime": params.queryParams.value.Time && dayjs(params.queryParams.value.Time[1]).format('YYYY-MM-DD'),
                            Status: params.queryParams.value.Status,
                            LevelId: params.cIndex.value,
                        }

                    }
                }).then(res => {
                    params.dataSource.value = res.Data.Data
                    params.pagination.value.total = res.Data?.TotalItemCount
                    params.pagination.value.loading = false
                })
            }
     

        },


        init: () => {

            getBrowserInfo().catch(err => { console.log(err) })
            if (proxy) {
                params.proxy.value = proxy
            }
    
            const key = `${window.location.pathname}Index`;
            const storedValue = Storage.get(key, true); // 获取原始值（字符串或 null）

            if (storedValue !== null && storedValue !== undefined && !isNaN(storedValue)) {
                params.cIndex.value = +Storage.get(`${window.location.pathname}Index`, true)
            }
            params.urlinfo.value = queryURLParams()
            params.yearList.value = getRecentYears()
            params.monthList.value = getMonthList()
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });

            setTimeout(() => {
                let info = Storage.get('AccountInfo', true)

                params.uinfo.value = info
                Request({
                    url: "/Account/createJwtToken",
                    method: 'post',
                    data: {
                        "userName": info && info.UserNo
                    }
                }).then(async res => {
                    Storage.set('token', res.Data,true)
                    methods.ITeamType().then(() => {
                        methods.getTableList(true)
           
                    })
             
                })
            }, 400)

        },

    }



    const template = {
        imageModel: previewCom(params, methods).imageModel,
        pdfPopModel: previewCom(params, methods).pdfPopModel,
    }
    return {
        ...params,
        ...methods,
        template
    }
}

export default Composition